import router from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // getToken from cookie
import { buildMenus } from '@/api/system/menu'
import { filterAsyncRouter } from '@/store/modules/permission'
import Cookies from 'js-cookie'
import Layout from '../layout/index'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + Config.title
  }
  NProgress.start()

  // 大屏带token跳转
  if (to.query.token) {
    setToken(to.query.token, true)
  }
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store
          .dispatch('GetInfo')
          .then((res) => {
            // 拉取user_info
            // 动态路由，拉取菜单
            loadMenus(next, to)
          })
          .catch((err) => {
            console.log(err)
            store.dispatch('LogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
        // 登录时未拉取 菜单，在此处拉取
      } else if (store.getters.loadMenus) {
        // 修改成false，防止死循环
        store.dispatch('updateLoadMenus').then((res) => {})
        loadMenus(next, to)
      } else {
        next()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

export const loadMenus = (next, to) => {
  /* var yf =[{"name":"在线取数","path":"/onlineAccess","hidden":false,"redirect":"noredirect","component":"Layout","alwaysShow":true,"meta":{"title":"在线取数","icon":"database","noCache":true},"children":[{"name":"QuerySql","path":"querySql","hidden":false,"component":"monitor/querySql/index","meta":{"title":"SQL式查询","icon":"database","noCache":true}},{"name":"dragQry","path":"dragQry","hidden":false,"component":"monitor/dragQuery/index","meta":{"title":"拖拽式查询","icon":"dept","noCache":true}}]},{"name":"工单管理","path":"/sqlgd","hidden":false,"redirect":"noredirect","component":"Layout","alwaysShow":true,"meta":{"title":"工单管理","icon":"edit","noCache":true},"children":[{"name":"check","path":"check","hidden":false,"component":"sqlgd/check/tabs","meta":{"title":"我的申请","icon":"skill","noCache":true}},{"name":"setting","path":"setting","hidden":false,"component":"sqlgd/setting/index","meta":{"title":"我的工单","icon":"timing","noCache":true}}]}]

  var admin = [{ 'name': 'SQL工单管理', 'path': '/gdEdit', 'hidden': false, 'redirect': 'noredirect', 'component': 'Layout', 'alwaysShow': true, 'meta': { 'title': 'SQL工单管理', 'icon': 'dept', 'noCache': true }, 'children': [{ 'name': 'implement', 'path': 'implement', 'hidden': false, 'component': 'gdEdit/implement/index', 'meta': { 'title': 'SQL工单', 'icon': 'qiniu', 'noCache': true }}, { 'name': 'history', 'path': 'history', 'hidden': false, 'component': 'gdEdit/history/index', 'meta': { 'title': 'SQL工单执行', 'icon': 'education', 'noCache': true }}] }, { 'path': '/db', 'hidden': false, 'component': 'Layout', 'children': [{ 'name': 'db', 'path': 'index', 'component': 'system/db/index', 'meta': { 'title': '数据库管理', 'icon': 'database', 'noCache': true }}] }, { 'path': '/appManager', 'hidden': false, 'component': 'Layout', 'children': [{ 'name': 'appManager', 'path': 'index', 'component': 'system/appManager/index', 'meta': { 'title': '应用管理', 'icon': 'app', 'noCache': true }}] }, { 'name': '系统监控', 'path': '/monitor', 'hidden': false, 'redirect': 'noredirect', 'component': 'Layout', 'alwaysShow': true, 'meta': { 'title': '系统监控', 'icon': 'monitor', 'noCache': true }, 'children': [{ 'name': 'OnlineUser', 'path': 'online', 'hidden': false, 'component': 'monitor/online/index', 'meta': { 'title': '在线用户', 'icon': 'Steve-Jobs', 'noCache': true }}, { 'name': 'Log', 'path': 'logs', 'hidden': false, 'component': 'monitor/log/index', 'meta': { 'title': '操作日志', 'icon': 'log', 'noCache': true }}, { 'name': 'ErrorLog', 'path': 'errorLog', 'hidden': false, 'component': 'monitor/log/errorLog', 'meta': { 'title': '异常日志', 'icon': 'error', 'noCache': true }}] }, { 'name': '系统管理', 'path': '/system', 'hidden': false, 'redirect': 'noredirect', 'component': 'Layout', 'alwaysShow': true, 'meta': { 'title': '系统管理', 'icon': 'system', 'noCache': true }, 'children': [{ 'name': 'User', 'path': 'user', 'hidden': false, 'component': 'system/user/index', 'meta': { 'title': '用户管理', 'icon': 'peoples', 'noCache': true }}, { 'name': 'Role', 'path': 'role', 'hidden': false, 'component': 'system/role/index', 'meta': { 'title': '角色管理', 'icon': 'role', 'noCache': true }}, { 'name': 'Menu', 'path': 'menu', 'hidden': false, 'component': 'system/menu/index', 'meta': { 'title': '菜单管理', 'icon': 'menu', 'noCache': true }}, { 'name': 'Dict', 'path': 'dict', 'hidden': false, 'component': 'system/dict/index', 'meta': { 'title': '字典管理', 'icon': 'dictionary', 'noCache': true }}] }]
  var yfgly = [{ 'name': 'SQL工单管理', 'path': '/gdEdit', 'hidden': false, 'redirect': 'noredirect', 'component': 'Layout', 'alwaysShow': true, 'meta': { 'title': 'SQL工单管理', 'icon': 'dept', 'noCache': true }, 'children': [{ 'name': 'approval', 'path': 'approval', 'hidden': false, 'component': 'gdEdit/approval/index', 'meta': { 'title': 'SQL工单审批', 'icon': 'Steve-Jobs', 'noCache': true }}, { 'name': 'implement', 'path': 'implement', 'hidden': false, 'component': 'gdEdit/implement/index', 'meta': { 'title': 'SQL工单', 'icon': 'qiniu', 'noCache': true }}, { 'name': 'history', 'path': 'history', 'hidden': false, 'component': 'gdEdit/history/index', 'meta': { 'title': 'SQL工单执行', 'icon': 'education', 'noCache': true }}] }]
  var res = []
  console.log('user', user)
  if (user.state) {
    var s = user.state
    // 三个用户名
    if (s.user.username == 'yf') {
      res = yf
    } else if (s.user.username == 'yfjl') {
      res = yfgly
    } else {
      res = admin
    }
  }
  const asyncRouter = filterAsyncRouter(res)
  asyncRouter.push({ path: '*', redirect: '/404', hidden: true })
  store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
    router.addRoutes(asyncRouter) // 动态添加可访问路由表
    next({ ...to, replace: true })
  })*/
  buildMenus().then((res) => {
    // 倒数第三插入
    // res[0].children.splice(4, 0, ({
    //   name: '关键指标',
    //   path: 'keyIndicators',
    //   component: 'monitorManage/keyIndicators/index.vue',
    //   meta: {
    //     title: '关键指标',
    //     icon: 'chart'
    //   }
    // }))

    // res[0].children.splice(0, 0, ({
    //   name: '集群监控信息总览',
    //   path: 'clusterOverview',
    //   component: 'monitorManage/clusterOverview/index.vue',
    //   meta: {
    //     title: '集群监控信息总览',
    //     icon: 'chart'
    //   }
    // }))

    const asyncRouter = filterAsyncRouter(res)
    console.log(Cookies.get('role'))
    if (Cookies.get('role') !== 'reader') {
      asyncRouter.splice(0, 0, {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        name: 'home',
        children: [
          {
            path: 'dashboard',
            component: () => import('@/views/home'),
            name: 'Dashboard',
            meta: { title: '首页', icon: 'index', affix: true, noCache: true }
          }
        ]
      },)
    }
    asyncRouter.push({ path: '*', redirect: '/404', hidden: true })
    store.dispatch('GenerateRoutes', asyncRouter).then(() => {
      // 存储路由
      router.addRoutes(asyncRouter) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
